/*
 * ManifestEditor.java
 *
 * Created on November 24, 2006, 9:14 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.netbeans.modules.manifesteditor.editor;

import java.io.IOException;
import java.util.logging.Logger;
import org.netbeans.core.spi.multiview.MultiViewDescription;
import org.netbeans.core.spi.multiview.MultiViewFactory;
import org.openide.cookies.EditCookie;
import org.openide.cookies.EditorCookie;
import org.openide.cookies.OpenCookie;
import org.openide.cookies.SaveCookie;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.text.CloneableEditorSupport;
import org.openide.text.DataEditorSupport;

/**
 *
 * @author Geertjan Wielenga
 */
public class ManifestEditorSupport extends DataEditorSupport implements OpenCookie, EditorCookie, EditCookie {
    
    private static Logger LOG = Logger.getLogger(ManifestEditorSupport.class.getName());
    
    final MultiViewDescription[] descriptions = {
        new ManifestTextView(this),
        new ManifestVisualView(this)
    };
    
    
    private ManifestEditorSupport(ManifestDataObject obj) {
        super(obj, new ManifestEnv(obj));
    }
    
    public static ManifestEditorSupport create(ManifestDataObject obj) {
        return new ManifestEditorSupport(obj);
    }
    
    protected CloneableEditorSupport.Pane createPane() {
        return (CloneableEditorSupport.Pane)MultiViewFactory.
                createCloneableMultiView(descriptions, descriptions[0]);
    }
    
    protected boolean notifyModified() {
        boolean retValue;
        retValue = super.notifyModified();
        if (retValue) {
            ManifestDataObject obj = (ManifestDataObject)getDataObject();
            obj.ic.add(env);
        }
        return retValue;
    }
    
    protected void notifyUnmodified() {
        super.notifyUnmodified();
        ManifestDataObject obj = (ManifestDataObject)getDataObject();
        obj.ic.remove(env);
    }
    
    private static final class ManifestEnv extends DataEditorSupport.Env implements SaveCookie {
        
        public ManifestEnv(ManifestDataObject obj) {
            super(obj);
        }
        
        public void save() throws IOException {
            ManifestEditorSupport ed = (ManifestEditorSupport)this.findCloneableOpenSupport();
            ed.saveDocument();
        }
        
        protected FileObject getFile() {
            return super.getDataObject().getPrimaryFile();
        }
        
        protected FileLock takeLock() throws IOException {
            return ((ManifestDataObject)super.getDataObject()).getPrimaryEntry().takeLock();
        }
        
    }
}
